
import EventManage from '../Framework/Managers/EventManage';
import { NetManage } from '../Framework/Managers/NetManage';
import { EventConfig } from '../Framework/SysConfig/SysConfig';
import { ProtoMag } from './Proto/ProtoMag';
import { Stype } from './Stype';

export class TcpClient {
    public static Instance: TcpClient = new TcpClient();

    public init() {
        EventManage.Instance.on(EventConfig.Net_Message, this.onRecvMsg, this);
    }

    // 事件名字---》事件订阅传过来的 net_message
    // udata: 网络收到数据;
    public onRecvMsg(eName: string, arrbuff: ArrayBuffer) {
        // 获取服务号，命令号;
        let dataView = new DataView(arrbuff);
        let stype = dataView.getInt16(0, true);
        let ctype = dataView.getInt16(2, true);

        // 获取我们的二进制数据;
        let uint8Buf: Uint8Array = new Uint8Array(arrbuff);
        let buffer = uint8Buf.subarray(4 + 4);

        // 反序列化二进制数据为一个对象
        let msgBody = ProtoMag.Instance.DeserializeMsg(ctype, buffer);
        EventManage.Instance.dispatchEvent(Stype[stype], ctype, msgBody);
    }

    public sendMsg(stype: number, ctype: number, data: any) {
        // step1: 序列化数据
        let buffer = ProtoMag.Instance.SerializeMsg(ctype, data);

        // step2: 按照协议，封装号我们的二进制数据包;
        let total_len = buffer.length + 2 + 2 + 4;
        let arrBuff = new ArrayBuffer(total_len); // 内存;
        let dataview = new DataView(arrBuff);     // DataView工具，buffer里面来写东西;
        // [stype, ctype, 4, bodyBuf]
        dataview.setInt16(0, stype, true); // offset, stype
        dataview.setInt16(2, ctype, true); // offset, ctype;
        dataview.setInt32(4, 0, true);
        let uint8Buf = new Uint8Array(arrBuff);
        uint8Buf.set(buffer, 8);
        // for (let i = 0; i < buff.byteLength; i++) {
        //     dataview.setUint8(8 + i, buff[i]);
        // }

        return arrBuff

        // step3: WebSocket发送出去
        NetManage.Instance.sendData(arrBuff);
    }
}

